<template>
  <div class='role-management-container treatment_div1 header'>
    <el-card class="box-card">
      <template #header>
        <div class="customerTitle1">
        <span>
            <span class="leve_title" >{{customer_order_list && customer_order_list.buyer_customer_name}}-{{title()}}</span>
         <div class="add_order_font1">
           <span>需求编码：{{customer_order_list && customer_order_list.order_no}} </span>

          <span style="margin-left: 10px;margin-right: 10px">订单状态：{{customer_order_list && customer_order_list.status_str}} </span>
          <span>销售员：{{customer_order_list && customer_order_list.sales_dept_name }}部门-{{customer_order_list && customer_order_list.undertaker_name}} </span>
         </div>
        </span>
          <div v-if="route.query.path ==2">
            <el-button
              @click="back"
            >
              <!--              {{route.query.path != 5? route.query.path == 1 ? '取消承接' :'取消':'返回'}}-->
              返回
            </el-button>
          </div>
        </div>
      </template>
   <div>
     <VabStep :steps="arr_approve"/>
   </div>
    </el-card>
    <el-card class="box-card">
      <template #header>
        <div class="customerTitle1">
          <span class="leve2_title leave3Title titleHead1">采购产品信息</span>
          <div>
<!--            <el-button size="small" @click="back">返回</el-button>-->
            <el-button v-if="route.query.path !=2" type="primary" @click="addOrder">
              创建订单
            </el-button>
          </div>
        </div>
      </template>
<!--      <div class="procureDiv1">
        <div class="procureDiv2">
          <div class="procureFont3">
            销售数量合计(个)
            <span class="procureFont4">
              {{customer_order_list && customer_order_list.order?.order_detail?.all_num || 0}}
            </span>
          </div>
        </div>
          <div class="procureDiv2">
            <div class="procureFont3">
              销售金额合计(￥)
              <span class="procureFont4">
                {{ customer_order_list && Number(customer_order_list.sale_price_all).toFixed(2)||0.00}}
              </span>
            </div>
          </div>
        <div class="procureDiv3" v-if=" customer_order_list && customer_order_list.order?.order_detail?.org_list?.length>0"  v-for="(items,index) in  customer_order_list.order?.order_detail?.org_list" :key="index">
          <div class="procureFont3">
            {{items.org_name}}
            <span class="procureFont4">
              {{items.sales_num}}/{{Number(items.price).toFixed(2)}}￥
            </span>
          </div>

        </div>
      </div>-->
      <div class="treatment_div">
        <span>
          <span>
            销售数量合计：
          </span>
          <span class="treatment_title">
             {{customer_order_list && customer_order_list.order?.order_detail?.all_num || 0}}个
          </span>
        </span>
        <span>
          <span>
           销售金额合计：
          </span>
          <span class="treatment_title">
           ￥ {{ customer_order_list && Number(customer_order_list.sale_price_all).toFixed(2)||0.00}}
          </span>
        </span>
        <span  v-if=" customer_order_list && customer_order_list.order?.order_detail?.org_list?.length>0"  v-for="(items,index) in  customer_order_list.order?.order_detail?.org_list" :key="index">
          <span>
           {{items.org_name}}：
          </span>
          <span class="treatment_title">
             {{items.sales_num}} 个-￥ {{Number(items.price).toFixed(2)}}
          </span>
        </span>
      </div>
      <div class="selectionLess">
        <el-table
          v-loading="loading"
          load="false"
          ref="multipleTableRef"
          border
          :data="customer_order_list?.detail || []"
          max-height="400px"
          style="width: 100%"
        >
          <el-table-column align="center" width="60" fixed="left"  v-if="route.query.path != 2">
            <template #default="scope">
              <div class="table_style">
                <el-checkbox :disabled="!scope.row.multiple" :model-value="multipleId?.includes(scope.row.id)"  @change="handleSelectionChange(scope.row)"  />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" width="60" fixed="left">
            <template #header>
              <span>
                  序号
                </span>
            </template>
            <template #default="scope">
              <div class="table_style">
<!--
                <el-checkbox v-if="route.query.path != 2" :disabled="!scope.row.multiple" :model-value="multipleId?.includes(scope.row.id)"  @change="handleSelectionChange(scope.row)"  />
-->
            <span
              style="margin-left: 5px"
              v-text="scope.$index + 1"
            ></span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="产品编码" align="center" min-width="100" fixed="left">
             <template #default="scope">
             <span
               class="ellipsis"
               v-text="_FieldFormat(scope.row.product_code,  '')"
             ></span>
           </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" min-width="200" fixed="left">
            <template #default="scope">
             <span
               class="ellipsis"
               v-text="_FieldFormat(scope.row.product_name,  '')"
             ></span>
           </template>
          </el-table-column>
<!--          <el-table-column label="品牌" align="center" width="100">
            <template #default="scope">
             <span
               class="ellipsis"
               v-text="_FieldFormat(scope.row.brand,  '')"
             ></span>
            </template>
          </el-table-column>-->
          <el-table-column label="采购数量" align="center" width="90">
            <template #default="scope">
             <span
               class="ellipsis numberMoney"
               v-text="_FieldFormat(scope.row.number,  '')"
             ></span>
            </template>
          </el-table-column>
          <el-table-column label="标记" align="center" min-width="200">
            <template #header  v-if="route.query.path !=2">
                <span class="spanFont">
                  *
                </span>
              <span>
                  标记
                </span>
            </template>
            <template #default="scope">
              <VabSelectForm v-if="route.query.path ==1" @change="flagChange(scope.row)"  :clearable="false"   v-model="scope.row.flag" :options="tax_flag_list"/>
              <span
                v-if="route.query.path ==2"
                class="ellipsis"
              >{{_FieldFormat(scope.row.flag,  '')}}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品类型" align="center" width="90">
            <template #default="scope">
             <span
               class="ellipsis"
             >{{_FieldFormat(scope.row.goods_type,  '')}}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售组织" align="center" width="210">
            <template #default="scope">
             <span
               class="ellipsis"
             >
               {{scope.row.settle_org_name?.toString() || '--' }}
             </span>
           </template>
          </el-table-column>
          <el-table-column label="销售数量" align="center" width="90">
            <template #default="scope">
             <span
               class="ellipsis numberMoney"
               :class="scope.row.ordered_num != scope.row.number ? 'fontColorNumber' : '' "
               v-text="_FieldFormat(scope.row.ordered_num,  '')"
             ></span>
            </template>
          </el-table-column>
          <el-table-column label="实发数量" align="center" width="90">
            <template #default="scope">
             <span
               class="ellipsis numberMoney"
               v-text="_FieldFormat(Number(scope.row.actual_num).toFixed(0),  '')"
             ></span>
            </template>
          </el-table-column>
          <el-table-column label="价格" align="center" width="100">
            <template #default="scope">
             <span
               class="ellipsis numberMoney"
               v-text="'￥'+_FieldFormat(scope.row.price,  '')"
             ></span>
           </template>
          </el-table-column>
          <el-table-column label="金额" align="center" width="120">
            <template #default="scope">
             <span
               class="ellipsis numberMoney"
               v-text="'￥'+_FieldFormat(scope.row.selling_price,  '')"
             ></span>
           </template>
          </el-table-column>
          <el-table-column label="订单号" align="center" width="150">
            <template #default="scope">
             <span
               class="ellipsis"
             >
              {{_FieldFormat(scope.row.order_uid,  '')}}
             </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <VabCard>
      <template #header>
        <span class="leve2_title leave3Title titleHead1" >采购基础信息</span>
      </template>
      <template #default >
        <el-row :gutter="24">
          <el-col
            v-for="(item, i) in procure_list"
            :key="i"
            :xs="24"
            :sm="12"
            :md="12"
            :lg="8"
            :xl="8"
          >
            <div class="detail-mode"  v-if="item.label != '详细地址'">
              <span class="label procureFont1">{{ item.label }}</span>
              <span class="text procureFont2">
                {{ item.value}}
                </span>
            </div>
            <div class="detail-mode" v-if="item.label == '详细地址'">
              <span class="label procureFont1">{{item.label}}</span>
              <span class="text height procureFont2">
                  {{ item.value}}
                </span>
            </div>
          </el-col>
        </el-row>
      </template>
    </VabCard>
    <CustomerNewOrder ref="pop_up" />
  </div>
</template>

<script setup lang="ts">
import {FieldFormat} from "/@/utils/utils";
import {ref} from "vue";
import {ElMessage} from "element-plus";
import router from "/@/router";
import {customerOrderInfo, customerUpdateProductCodeSign} from "/@/api/dms/customerOrder";
import App from "/@/App.vue";
import CustomerNewOrder from './CustomerNewOrder.vue'
import {orderGroupInfo, orderGroupInsert} from "/@/api/dms/order/group";
import {el} from "element-plus/es/locale";
import { convertToTree, flattenArray } from "/@/views/order_management/orderText";
import _ from "lodash";

defineOptions({
    name: 'Treatment',
  })
const _FieldFormat = (value: string, type = '') => {
  return FieldFormat(value, type)
}
const route:any = useRoute()
const multipleTableRef = ref<any>(undefined)
const pop_up:any = ref<any>(undefined)
const customer_order_list = ref<any>(undefined)
const orderPath2:any = ref(localStorage.getItem('orderPath2'))
const group =ref()
const loading=ref(false)
const procure_list = ref([
  {label:'买方',value:''},
  {label:'开票类型',value:''},
  {label:'发票抬头',value:''},
  {label:'公司税号',value:''},
  {label:'期望运输方式',value:''},
  {label:'运费付款方式',value:''},
  {label:'收货地址',value: ''},
  {label:'详细地址',value:''},
  {label:'收货联系人',value:''},
  {label:'联系电话',value:''},
  {label:'创建人',value:''},
  {label:'创建时间',value:''},
  {label:'对接商务',value:''},
])
const tax_flag_list = ref<any>([{value:'当前库存满足、尽快发货',label:'当前库存满足、尽快发货'},{value:'当前库存紧张，部分发货',label:'当前库存紧张，部分发货'},{value:'当前库存不足，暂不发货',label:'当前库存不足，暂不发货'},{value:'已和客户确认修改产品',label:'已和客户确认修改产品'},{value:'已和客户确认新增产品',label:'已和客户确认新增产品'},{value:'补充赠品',label:'补充赠品'},{value:'已和客户确认删除产品',label:'已和客户确认删除产品'}])
// 标记
const flagChange = (va:any)=>{
  customerUpdateProductCodeSign({id:va.id,order_no:customer_order_list.value.order_no,flag:va.flag,}).then((data:any)=>{
    if(data.code == 200){
      getInfo()
    }
  })
}
// ***********
const arr_approve = ref<any>([
  { title: '客户需求', active: true, path:`/order/treatment?path=${route.query.path}&id=${route.query.id}`},
  { title: '销售订单', active: false,},
  { title: '销售出库单', active: false,},
  { title: '快递运输', active: false },
  { title: '收货确认', active: false },
])
// ******************
let multipleDate =reactive<any>([])
let multipleId =ref<any>([])
  const handleSelectionChange = (val: any) => {
    const arrList =  convertToTree(customer_order_list.value.detail)
    if(multipleDate.length == 0){
      const arr = customer_order_list.value?.detail.filter((item:any)=> item.multiple).filter((v:any)=> v.settle_org_uid == val.settle_org_uid )
      multipleDate = arr
      const result = flattenArray(arrList.filter((item1:any) => {
        return arr.some((item2:any) => {
          return item1.product_code === item2.product_code;
        });
      }));
      multipleId.value = result.map((item:any)=> item.id)
    }else {
      if(multipleId.value.includes(val.id)){
        multipleDate = multipleDate.filter((va:any)=> va.id !== val.id)
        const result = flattenArray(arrList.filter((item1:any) => {
          return multipleDate.some((item2:any) => {
            return item1.product_code === item2.product_code;
          });
        }));
        multipleId.value = result.map((item:any)=> item.id)
      }else {
        if(val.settle_org_uid !== multipleDate[multipleDate.length-1].settle_org_uid){
          ElMessage({
            message: '不同销售组织的产品不能创建在同一订单中。',
            type: 'warning',
          })
        }else {
          const arr = customer_order_list.value?.detail.filter((item:any)=> item.multiple).filter((v:any)=> v.settle_org_uid == val.settle_org_uid )
          multipleDate = arr
          const result = flattenArray(arrList.filter((item1:any) => {
            return arr.some((item2:any) => {
              return item1.product_code === item2.product_code;
            });
          }));
          multipleId.value = result.map((item:any)=> item.id)
        }

      }
    }
}

const addOrder = ()=>{
  multipleDate= multipleDate.filter((i:any)=> i.flag != '已和客户确认删除产品') || []
  const arr = convertToTree(customer_order_list.value.detail.map((item:any)=>{return {...item,type:'无价目表', discount_rate: item.goods_type == '正品'? 0 : 100}}))
  const result = arr.filter((item1:any) => {
    return multipleDate.some((item2:any) => {
      return item1.product_code === item2.product_code;
    });
  });
  if(multipleDate.length > 0 ){
    multipleDate= multipleDate.filter((i:any)=> i.flag != '已和客户确认删除产品') || []
    orderGroupInsert({type:1,c_order_uid:customer_order_list.value.order_no}).then((data:any)=>{
      if(data.code == 200){
        group.value = data.data
        pop_up.value.getGroupList =  data.data
      }
    })
    pop_up.value.dialogVisibles = true
    pop_up.value.submit = false
    pop_up.value.copyList = {...customer_order_list.value,detail:result}
  }else {
    ElMessage({
      message: '请先选择订单',
      type: 'warning',
    })
  }
}
const getInfo = ()=>{
  if( route.query.id){
    loading.value = true
    customerOrderInfo({order_no:route.query.id}).then((data:any)=>{
      if(data.code == 200){
        loading.value = false
        customer_order_list.value = {
          ...data.data,
          detail:data.data.detail?.map((i:any)=>{
            return{
              ...i,
              multiple: i.ordered_num < i.number && i.flag != '已和客户确认删除产品' && i.goods_type !== '赠品'
            }
          }),
        }
      }
    })
  }
  orderGroupInsert({type:1,c_order_uid:route.query.id}).then((data:any)=>{
    if(data.code == 200){
      group.value = data.data
    }
  })
}

watch(customer_order_list,()=>{
  if(customer_order_list){
    procure_list.value = [
      {label:'买方',value:customer_order_list.value.buyer_customer_name ||''},
      {label:'开票类型',value:customer_order_list.value.invoice_type_str||''},
      {label:'发票抬头',value:customer_order_list.value.invoice_str|| ''},
      {label:'公司税号',value:customer_order_list.value.tax_number},
      {label:'期望运输方式',value:customer_order_list.value.transport_type_str},
      {label:'运费付款方式',value:customer_order_list.value.pay_type == 1 ? '运费到付' : '运费预付' },
      {label:'收货地址',value: customer_order_list.value.shipping_address},
      {label:'详细地址',value:customer_order_list.value.address},
      {label:'收货联系人',value:customer_order_list.value.shipping_contact},
      {label:'联系电话',value:customer_order_list.value.shipping_tel},
      {label:'创建人',value:customer_order_list.value.create_user_name},
      {label:'创建时间',value:customer_order_list.value.create_at},
      {label:'对接商务',value:customer_order_list.value.undertaker_name},
    ]
  }
})
const selectable =(row:any)=>{
  return row.ordered_num < row.number && row.flag != '已和客户确认删除产品' && row.goods_type !== '赠品'
}

onMounted(()=>{
  getInfo()
})
const back = ()=>{
  // router.push('/order/customerOrder')
  if(orderPath2.value == 1){
    router.push('/order/customerOrder')
  }else {
    router.push('/order/orderQuery')
  }
}
watchEffect(()=>{
  if(customer_order_list.value && customer_order_list.value.order?.order_detail?.list.length >0 && group.value){
    if(customer_order_list.value && customer_order_list.value.stock_out.length >0){//判断 是否存在销售出库单
      if(customer_order_list.value.is_express){//判断 是否存在快递运输
        arr_approve.value = [
          { title: '客户需求', active: true, path:`/order/treatment?path=${route.query.path}&id=${route.query.id}`},
          { title: '销售订单', active: true, path:`/order/addOrder?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}` },
          { title: '销售出库单', active: true, path:`/order/retrieval?path=${route.query.path}&id=${ group.value.uid}&order=${route.query.id || 0}` },
          { title: '快递运输', active: true,path:`/order/expressCompany?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}`  },
          { title: '收货确认', active: true,path:`/order/receipt?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}` },
        ]
      }else {
        arr_approve.value = [
          { title: '客户需求', active: true, path:`/order/treatment?path=${route.query.path}&id=${route.query.id}`},
          { title: '销售订单', active: true, path:`/order/addOrder?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}` },
          { title: '销售出库单', active: true, path:`/order/retrieval?path=${route.query.path}&id=${ group.value.uid}&order=${route.query.id || 0}` },
          { title: '快递运输', active: false,path:`/order/expressCompany?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}`  },
          { title: '收货确认', active: false,path:`/order/receipt?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}` },
        ]
      }

    }else {
      arr_approve.value = [
        { title: '客户需求', active: true, path:`/order/treatment?path=${route.query.path}&id=${route.query.id}`},
        { title: '销售订单', active: true, path:`/order/addOrder?path=${route.query.path}&id=${ group.value.uid || 0}&order=${route.query.id}` },
        { title: '销售出库单', active: false, path:`/order/retrieval?path=${route.query.path}&id=${ group.value.uid}` },
        { title: '快递运输', active: false },
        { title: '收货确认', active: false },
      ]
    }
  }
})
const title=()=>{
  if(route.query.path == 1){
    return '销售订单'
  }else if(route.query.path == 2){
    return '销售订单详情'
  }
}
</script>

<style lang="scss" scoped>
@import "../../index";
.fontColorNumber {
  color: #ffb74d;
}
</style>

